class GamePlayingPanel extends egret.Sprite {
	public static CHANGEPANEL: string = "gamePlayingChangePanel";
	private bg: egret.Bitmap;

	// UI布局
	// 左侧玩家
	private leftPlayer: Player;
	// 右侧玩家
	private rightPlayer: Player;
	// 底牌
	private dipai;
	// 出牌区域
	private showPai;
	// 退出按钮
	private exitBtn: egret.Bitmap;
	// 我的区域
	private myPlayer: Player;
	// 按钮操作
	private btns;
	// 退出按钮

	// 重新开始
	public resetBtn: MBtn;
	// 玩家用户组
	private playerArr = [];
	// 抢地主叫分
	private robLanScore: RobLanScore;
	// 当前的叫分
	private currentScore = 0;
	// 有几个玩家叫分了
	private round = 0;
	// 记录当前叫分的玩家
	private currentLandlord = null;

	// 我的玩家出牌按钮组
	public playBtns: PlayBtns;
	// 提示出牌的下标
	public promptIndex: number = 0;



	// 底牌
	private hiddenCards: Array<any> = [];
	// 发牌计时器
	private faPaiTimer: egret.Timer;

	public constructor() {
		super();
		// 初始化页面 后面加了
		this.init();
	}
	private init() {
		this.bg = new egret.Bitmap(RES.getRes("gameStartBg_png"));
		this.addChild(this.bg);
		// 设置宽高
		this.bg.width = Data.getStageW();
		this.bg.height = Data.getStageH();

		// 左侧玩家
		this.leftPlayer = new Player('left-player', true, 30, 80, 180, 280);
		this.addChild(this.leftPlayer);
		this.playerArr.push(this.leftPlayer);

		// 右侧玩家
		this.rightPlayer = new Player('right-player', true, 0, 80, 180, 280);
		this.addChild(this.rightPlayer);
		this.rightPlayer.x = Data.getStageW() - 30 - 180;
		this.playerArr.push(this.rightPlayer);


		// 底牌
		this.dipai = new egret.Sprite();
		// this.dipai.graphics.beginFill(0xff0000);
		this.dipai.graphics.drawRect(Data.getStageW() / 2, 9, 270, 100);
		this.dipai.graphics.endFill();
		this.addChild(this.dipai);
		// 设置锚点为右上角 
		Data.setAnchorOffset(this.dipai, this.dipai.width / 2, 0);

		// 出牌区域
		this.showPai = new egret.Sprite();
		// this.showPai.graphics.beginFill(0xff0000);
		this.showPai.graphics.drawRect(Data.getStageW() / 2, Data.getStageH() / 2 - 71, 646, 223);
		this.showPai.graphics.endFill();
		this.addChild(this.showPai);
		// 设置锚点为右上角 
		Data.setAnchorOffset(this.showPai, this.showPai.width / 2, this.showPai.height / 2);

		// 按钮区域
		this.btns = new egret.Sprite();
		// this.btns.graphics.beginFill(0xff0000);
		this.btns.graphics.drawRect(0, Data.getStageH() - 275, Data.getStageW(), 50);
		this.btns.graphics.endFill();
		this.addChild(this.btns);
		// 初始化我的抢地主ui
		this.robLanScore = new RobLanScore();

		// 出牌按钮组
		this.playBtns = new PlayBtns();
		this.addChild(this.playBtns);
		

		// 本人区域
		this.myPlayer = new Player('my-player', false, 0, Data.getStageH() - 220, Data.getStageW(), 215);
		this.addChild(this.myPlayer);
		this.playerArr.push(this.myPlayer);
		// 记录所有玩家
		Data.playerArr = this.playerArr;
		// exitBtn
		// this.exitBtn = new egret.Bitmap(RES.getRes())


		// 改变控件的深度...放置到最上面显示
		this.setChildIndex(this.leftPlayer, 99);
		this.setChildIndex(this.rightPlayer, 99);

		// 添加游戏中的点击事件
		this.addEventListener(PlayingTapEvent.PLAYING_TAP_EVENT, this.playingTap, this);
		// 设置游戏玩家的下一家
		this.leftPlayer.nextPlayer = this.myPlayer;
		this.myPlayer.nextPlayer = this.rightPlayer;
		this.rightPlayer.nextPlayer = this.leftPlayer;

		// 重新开始游戏
		this.resetBtn = new MBtn("primary", (Data.getStageW() - 90)/ 2 ,( Data.getStageH() - 40)/2, 90, 40);
		this.resetBtn.btnText.text = '开始游戏';
		this.resetBtn.btnText.size = 16;
		this.resetBtn.touchEnabled = true;
		this.resetBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.beginGame,this);
		this.addChild(this.resetBtn);
	}
	private beginGame(){
		this.start();
		if(this.resetBtn.parent){
			this.resetBtn.parent.removeChild(this.resetBtn);
		}
		
	}
	// 开启监听
	public start() {

		// 清空玩家所有的手牌
		for (var i: number = 0; i < this.playerArr.length; i++) {
			var p: Player = this.playerArr[i];
			p.cardList = [];
			for (var j = 0; j < p.myCardsObj.length; j++) {
				var bitMap = p.myCardsObj[j];
				if (bitMap.parent) {
					bitMap.parent.removeChild(bitMap);
				}
			}
			// 清空所有出牌区域的牌
			for (var j = 0; j < p.myPrevPlayCardsObj.length; j++) {
				var bitMap = p.myPrevPlayCardsObj[j];
				if (bitMap.parent) {
					bitMap.parent.removeChild(bitMap);
				}
			}
			p.myCardsObj = [];
			p.robLanText.text = '';
			// 置空地主状态
			p.isLandlord = false;
			// 清空用户头像
			if(p.portrait.parent){
				p.portrait.parent.removeChild(p.portrait)
			}
			
			
		}
		// 清空底牌
		this.hiddenCards = [];
		// 清空抢地主轮数
		this.round = 0;
		// 发牌配置
		this.fapai();
		// 开始发牌
		this.faPaiTimer.start();
		// 开始抢地主

	}
	private playingTap(e: PlayingTapEvent) {
		var num = parseInt(e.eventType)
		// 根据按钮里是否包含数字,来判断是抢分的按钮组还是出牌的按钮组
		if (isNaN(num) && e.eventType != "不叫") {
			this.playBtnsHandler(e.eventType);
		} else {
			this.myProvideScore(num);

		}
	}
	/**
	 * 出牌按钮组的逻辑
	*/
	private playBtnsHandler(type) {
		switch (type) {
			case '不出':
				// 不出操作
				var l = PlayCard.readyCards.length;
				if (l > 0) {
					for (var i: number = 0; i < l; i++) {
						for (var j: number = 0; j < this.myPlayer.myCardsObj.length; j++) {
							var bitMap = this.myPlayer.myCardsObj[j];
							if (bitMap.info.val == PlayCard.readyCards[i].val && bitMap.info.type == PlayCard.readyCards[i].type) {
								// 归位
								bitMap.isSelected = false;
								bitMap.anchorOffsetY = 0;
								break;
							}
						}
					}
				}
				// 隐藏出牌按钮
				var arr = SceneManager.getInstance().gamePlayingPanel.playBtns.btnArr;
				for (var i: number = 0; i < arr.length; i++) {
					if (arr[i].parent) {
						arr[i].parent.removeChild(arr[i])
					}
				}
				// 文字提示
				this.myPlayer.robLanText.text = '过!';
				this.myPlayer.robLanText.x = (Data.getStageW() - this.myPlayer.robLanText.width) / 2

				break;
			case "提示":


				// 先复位
				var l = PlayCard.readyCards.length;
				if (l > 0) {
					for (var i: number = 0; i < l; i++) {
						for (var j: number = 0; j < this.myPlayer.myCardsObj.length; j++) {
							var bitMap = this.myPlayer.myCardsObj[j];
							if (bitMap.info.val == PlayCard.readyCards[i].val && bitMap.info.type == PlayCard.readyCards[i].type) {
								// 归位
								bitMap.isSelected = false;
								bitMap.anchorOffsetY = 0;
								break;
							}
						}
					}
				}


				var promptList = PlayCard.prompt(PlayCard.winCard, this.myPlayer);
				console.log(promptList);

				// promptList.sort(function (a, b) {
				// 	var va = AILogic.maxCards(a,GameRule.ONE);
				// 	var vb = AILogic.maxCards(b,GameRule.ONE);
				// 	if (va.val === vb.val) {
				// 		return va.type > vb.type ? 1 : -1;
				// 	} else if (va.val > vb.val) {
				// 		return -1;
				// 	} else {
				// 		return 1;
				// 	}
				// })

				if (promptList.length <= 0) {
					// 过
					this.myPlayer.robLanText.text = '没有大过的牌!';
					this.myPlayer.robLanText.x = (Data.getStageW() - this.myPlayer.robLanText.width) / 2
					return;
				}

				if (this.promptIndex == promptList.length) {
					this.promptIndex = 0;
				}


				// for (var i: number = 0; i < promptList.length; i++) {
				var cards = promptList[this.promptIndex];
				if (!cards || cards.length <= 0) {
					return;
				}
				for (var j: number = 0; j < cards.length; j++) {
					// 找到每一张牌的数据,之后在对应找到相应的bitmap
					for (var k: number = 0; k < this.myPlayer.myCardsObj.length; k++) {
						var cardObj = this.myPlayer.myCardsObj[k];
						if (cards[j].val == cardObj.info.val && cards[j].type == cardObj.info.type) {
							cardObj.cardClick();
						}

					}

				}

				// }

				// 增加提示牌组的下标
				this.promptIndex++;

				return;
			// break;
			// 提示操作
			case '出牌':
				// 记录本轮牌的最大者
				PlayCard.roundWinner = this.myPlayer;
				// delete result.cardList;
				PlayCard.winCard = PlayCard.getReadyCardsKind();
				console.log(PlayCard.getReadyCardsKind());
				// 出牌操作
				var l = PlayCard.readyCards.length;
				if (l > 0) {
					// 记录出牌区的牌
					this.myPlayer.myPrevPlayCardsObj = [];
					// 先计算当前牌的总宽度
					var currentL = 70 + 30 * (l - 1);
					for (var i: number = 0; i < l; i++) {
						for (var j: number = 0; j < this.myPlayer.myCardsObj.length; j++) {
							var bitMap = this.myPlayer.myCardsObj[j];
							if (bitMap.info.val == PlayCard.readyCards[i].val && bitMap.info.type == PlayCard.readyCards[i].type) {
								// 添加到出牌区
								this.myPlayer.myPrevPlayCardsObj.push(bitMap);
								// 从源数据中删除
								this.myPlayer.myCardsObj.splice(j, 1);
								// 归位
								bitMap.isSelected = false;
								bitMap.anchorOffsetY = 0;
								// 修改位置
								bitMap.width = 70;
								bitMap.height = 100;
								bitMap.x = (Data.getStageW() / 2 - currentL / 2) + 30 * i;
								bitMap.y = 250;
								break;
							}
						}
					}
					// 删除源数据
					for (var i: number = 0; i < l; i++) {
						for (var j: number = 0; j < this.myPlayer.cardList.length; j++) {
							var card = this.myPlayer.cardList[j];
							if (card.val == PlayCard.readyCards[i].val && card.type == PlayCard.readyCards[i].type) {
								// 从源数据中删除
								this.myPlayer.cardList.splice(j, 1);
								break;
							}
						}
					}
				}


				// 重新整理手牌区域
				var currentL = 70 + 30 * (this.myPlayer.myCardsObj.length - 1);
				for (var j: number = 0; j < this.myPlayer.myCardsObj.length; j++) {
					var bitMap = this.myPlayer.myCardsObj[j];
					// 整理
					bitMap.anchorOffsetY = 0;
					// 修改位置
					bitMap.x = (Data.getStageW() / 2 - currentL / 2) + 30 * j;
				}
				// 隐藏出牌按钮
				var arr = SceneManager.getInstance().gamePlayingPanel.playBtns.btnArr;
				for (var i: number = 0; i < arr.length; i++) {
					if (arr[i].parent) {
						arr[i].parent.removeChild(arr[i])
					}
				}
				console.log('我的牌还有' + this.myPlayer.myCardsObj.length + '张');

				if (this.myPlayer.myCardsObj.length == 0) {
					PlayCard.judgeWiner(this.myPlayer);
					return;
				}
				break;
		}

		//下一家
		PlayCard.playing(this.rightPlayer);
	}


	/**
	 * 发牌
	*/
	private fapai() {
		// 获取所有牌的信息
		var cardsArr = RES.getRes("cardsData_json").slice(0);
		// 抽三张底牌出来先
		for (var i: number = 0; i < 3; i++) {
			this.hiddenCards.push(this.getOneCard(cardsArr));
		}

		// 左侧玩家手牌
		for (var i: number = 0; i < 17; i++) {
			// Player.leftCards.push(Player.getOneCard(cardsArr));
			// 改造把数据放到对象里去
			this.leftPlayer.cardList.push(this.getOneCard(cardsArr));
		}

		// 右侧玩家手牌
		for (var i: number = 0; i < 17; i++) {
			// Player.rightCards.push(Player.getOneCard(cardsArr));
			this.rightPlayer.cardList.push(this.getOneCard(cardsArr));
		}
		// 我的牌
		this.myPlayer.cardList = cardsArr;
		// 对所有手牌进行排序
		this.hiddenCards.sort(Data.bTos)
		this.leftPlayer.cardList.sort(Data.bTos)
		this.rightPlayer.cardList.sort(Data.bTos)
		// 玩家的手牌暂时不需要排序.		
		// Player.myCards.sort(Data.bTos)			

		// 开始发牌的动画
		this.faPaiTimer = new egret.Timer(200, 17);
		// 监听发牌时间控制器
		this.faPaiTimer.addEventListener(egret.TimerEvent.TIMER, this.timerHandler, this);
		this.faPaiTimer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, this.timerCompleteHandler, this);
		this.dipai.cardList = [];

		// 底牌
		for (var i: number = 0; i < 3; i++) {
			var bitMap = new Card();
			bitMap.width = 70;
			bitMap.height = 100;
			this.dipai.addChild(bitMap);
			this.dipai.cardList[i] = bitMap;
			bitMap.x = Data.getStageW() / 2 + (70 + 35) * i;
			bitMap.y = 10;
		}
	}
	private timerHandler(e: egret.TimerEvent) {
		// 计时器执行的次数
		var index = this.faPaiTimer.currentCount;
		// 玩家添加纸牌
		for (var i: number = 0; i < this.playerArr.length; i++) {
			var player = this.playerArr[i];
			player.insertOneCard(index);
		}
	}
	// 获取一张牌
	private getOneCard(arr) {
		// 随机删除并返回这张牌,类型是obj
		return arr.splice(Math.floor(Math.random() * arr.length), 1)[0];
	}

	private timerCompleteHandler(e: egret.TimerEvent) {
		// 先移除两个监听
		if (this.faPaiTimer.hasEventListener(egret.TimerEvent.TIMER)) {
			this.faPaiTimer.removeEventListener(egret.TimerEvent.TIMER, this.timerHandler, this);
		}
		if (this.faPaiTimer.hasEventListener(egret.TimerEvent.TIMER_COMPLETE)) {
			this.faPaiTimer.removeEventListener(egret.TimerEvent.TIMER_COMPLETE, this.timerCompleteHandler, this);
		}
		// 触发抢地主流程
		this.robLandlord();
	}

	// 抢地主
	private robLandlord() {
		var self = this;
		// 随机一个0~2之间的数
		var num = Math.floor(Math.random() * 3);
		// 声明第一个触发抢地主的角色,默认为我
		var player = self.myPlayer;
		if (num == 1) {
			player = self.leftPlayer;
		} else if (num == 2) {
			player = self.rightPlayer;
		}

		this.provideScore(player);

	}


	/**
	 * 轮流叫分
	*/
	private provideScore(player) {
		var self = this;
		// 轮流叫分
		if (player.isAI) {
			// AI 玩家随机出分
			// 隐藏我的叫分面板
			for (var i: number = 0; i < this.robLanScore.btnArr.length; i++) {
				var btn = this.robLanScore.btnArr[i];
				if (btn.parent) {
					btn.parent.removeChild(btn);
				}
			}

			var score = 0;
			// 牌型分析一下,把牌归类
			setTimeout(function () {

				AILogic.analyse(player);
				// AI牌型评分,来选择是否叫地主
				var s = AILogic.judgeScore(player);

				if (s < 4 && s > self.currentScore) {
					self.currentScore = s;
					player.robLanText.text = s + '分';
					// 记录当前叫分的玩家
					self.currentLandlord = player;
					if (s === 3) {
						// 三分,直接当地主
						self.setLanlord(player);
						return;
					}
				} else {
					// 不叫
					player.robLanText.text = '不叫';

				}
				if (++self.round === 3) {
					// 三家都叫过分了
					if (self.currentLandlord) {
						// 有人叫分,则它是地主
						self.setLanlord(self.currentLandlord);
					} else {
						// 没有人叫分,重新发牌
						setTimeout(function () {
							self.start();
						}, 1000);;
					}
				} else {
					// 下一个玩家开始叫分
					self.provideScore(player.nextPlayer);
				}
			}, 1000);

		} else {
			// 我叫分,出分面板显示
			this.addChild(this.robLanScore);
			this.robLanScore.addChild(this.robLanScore.btnArr[3]);
			this.robLanScore.addChild(this.robLanScore.btnArr[2]);
			if (this.currentScore < 2) {
				this.robLanScore.addChild(this.robLanScore.btnArr[1]);
			}
			if (this.currentScore < 1) {
				this.robLanScore.addChild(this.robLanScore.btnArr[0]);
			}

			// this.myProvideScore(4)
		}

	}

	// 设置地主
	private async setLanlord(player: Player) {
		await Data.sleep(1000);
		var self = this;
		// 设置该玩家为地主
		player.isLandlord = true;
		// 全局记录地主
		Data.currentLandlord = player;
		console.log('地主就是:' + player.name);
		// 隐藏我的叫分面板
		for (var i: number = 0; i < this.robLanScore.btnArr.length; i++) {
			var btn = this.robLanScore.btnArr[i];
			if (btn.parent) {
				btn.parent.removeChild(btn);
			}
		}
		// 隐藏所有玩家的叫分提示
		for (var i: number = 0; i < self.playerArr.length; i++) {
			var p = self.playerArr[i];
			p.robLanText.text = '';
		}
		// 显示底牌
		for (var i: number = 0; i < this.hiddenCards.length; i++) {
			var bitMap = this.dipai.cardList[i];
			bitMap.texture = RES.getRes(this.hiddenCards[i].icon.split('.')[0]);
		}
		// 显示角色头像
		for (var i: number = 0; i < self.playerArr.length; i++) {
			var p = self.playerArr[i];
			if (p == player) {
				p.portrait.texture = RES.getRes('landlord_png')
			} else {
				p.portrait.texture = RES.getRes('peasant_png')
			}
			p.addChild(p.portrait);
		}
		// 把底牌添加到地主的牌组里
		for (var i: number = 0; i < self.hiddenCards.length; i++) {
			// 增加地主的底牌
			player.cardList.push(self.hiddenCards[i]);
			player.insertOneCard(player.myCardsObj.length + 1);
		}
		// 排序
		player.cardList.sort(Data.bTos);
		// 重新分析牌型
		AILogic.analyse(player);

		// 由地主开发出牌
		PlayCard.playing(player);

	}
	// 玩家 我 抢地主给分
	private myProvideScore(score) {
		var self = this;
		if (score < 4) {
			self.currentScore = score;
			self.myPlayer.robLanText.text = score + '分';
			self.currentLandlord = self.myPlayer;
			if (score === 3) {
				self.setLanlord(this.myPlayer);
				return;
			}
		} else {
			self.myPlayer.robLanText.text = '不叫';
		}

		if (++self.round === 3) {
			// 三家都叫过分了
			if (self.currentLandlord) {
				// 有人叫分,则它是地主
				self.setLanlord(self.currentLandlord);
			} else {
				// 没有人叫分,重新发牌
				setTimeout(function () {
					self.start();
				}, 1000);;
			}
		} else {
			// 下一个玩家开始叫分
			self.provideScore(this.myPlayer.nextPlayer);
		}

	}

}